package com.hhh.Controller;

import com.hhh.Pojo.Employee;
import com.hhh.Pojo.Result;
import com.hhh.Service.LoginService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
@RequestMapping("/employee")
public class LoginController {
    @Autowired
    LoginService loginService;

    //    登录
//    登录
//    登录
    @PostMapping("/login")
    public Result<Employee> Login(@RequestBody Employee employee, HttpServletRequest request) {
//        对密码进行加密处理
        String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        employee.setPassword(password);
        Employee returnemployee = loginService.Login(employee);
//        判断用户是否存在
        if (returnemployee == null)
            return Result.error("登录失败");
        else {
//            校验密码
            if (returnemployee.getPassword().equals(employee.getPassword())) {
//                校验用户状态
                if (returnemployee.getStatus() == 1) {
//                    存入用户id
                    request.getSession().setAttribute("employee", returnemployee.getId());
                    log.info("登录系统");
//                    要把查询的数据返回，admin用户有特殊权限
                    return Result.success(returnemployee);
                } else
                    return Result.error("用户被禁用");
            }
            return Result.error("登录失败");
        }
    }

    //    登出
//    登出
//    登出
    @PostMapping("/logout")
    public Result LogOut(HttpServletRequest request) {
//        移除Session里面的数据
        request.getSession().removeAttribute("employee");
        log.info("登出系统");
        return Result.success(null);
    }


}
